<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>4_getSnapshotBeforeUpdate的使用场景</title>
    <style>
        .list {
            width: 300px;
            height: 150px;
            background: #e3e4e5;
            overflow: auto;
            margin: auto;
            text-align: center;
        }

        .news {
            height: 30px;
        }
    </style>
</head>
<body>
<!--准备好一个容器-->
<div id="test">

</div>
<!--核心库引入顺序，必须先是核心库然后在引入dom库-->
<script src="../js/react.development.js" crossorigin></script>
<!--用于支持react操作dom-->
<script src="../js/react-dom.development.js"></script>
<!--引入babel，用于将jsx转为js-->
<script src="../js/babel.min.js"></script>
<script type="text/babel">
    class NewsList extends React.Component {
        state = {
            newsArr: []
        }

        componentDidMount() {
            setInterval(() => {
                //获取原状态
                let {newsArr} = this.state
                //摸你网络请求
                const news = '新闻' + (newsArr.length + 1)
                //更新状态
                this.setState({newsArr: [news, ...newsArr]})
            }, 1000)
        }

        getSnapshotBeforeUpdate() {
            return this.refs.list.scrollHeight;
        }

        componentDidUpdate(prevProps, prevState, scrollHeight) {
            this.refs.list.scrollTop += this.refs.list.scrollHeight - scrollHeight
        }

        render() {
            return (
                <div className="list" ref="list">
                    {
                        this.state.newsArr.map((n, index) => {
                            return <div key={index} className="news">{n}</div>
                        })
                    }
                </div>
            )
        }
    }

    ReactDOM.render(<NewsList/>, document.getElementById('test'))
</script>
</body>
</html>